import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage } from "umi-plugin-react/locale";
import { Row, Col, Card, Button, Input, message, Icon, Form } from "antd";
import styles from "./index.less";
import { routerRedux } from "dva/router";

import ReactJson from "react-json-view";

@connect(({ process, loading }) => ({
	process,
	loading: loading.effects["process/fetch"],
}))
class ProcessTemplate extends Component {
	constructor(props) {
		super(props);
		this.state = {
			loading: false,
			api: {},
		};
	}

	componentDidMount() {
		if (this.props.location.query.api) {
			this.setState({ api: JSON.parse(this.props.location.query.api) });
		}
	}

	backList() {
		const { dispatch } = this.props;
		dispatch(routerRedux.push("/knowledgeDesign/customApi"));
	}

	handleSubmit = (e) => {
		e.preventDefault();
		this.props.form.validateFields((err, values) => {
			let obj = values;
			if (!err) {
				this.setState({ loading: true }, () => {
					this.testApiById(obj);
				});
			}
		});
	};

	testApiById = (obj) => {
		const { dispatch } = this.props;
		let apiObj = obj;
		apiObj.id = this.state.api.id;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "customApi/testApi",
				payload: apiObj,
				callback: (res) => {
					if (res.code === -1) {
						this.setState({ loading: false });
						return false;
					};
					this.setState({ loading: false, result: res, show: true }, () => {
						message.info("请求成功");
					});
				},
			});
		});
	};

	componentDidMount() {
		const apiInfo = JSON.parse(this.props.location.query.api);
		this.setState({ api: apiInfo });
	}

	render() {
		const apiInfo = JSON.parse(this.props.location.query.api);

		const { getFieldDecorator } = this.props.form;
		const formItemLayout = {
			labelCol: {
				xs: { span: 24 },
				sm: { span: 4 },
			},
			wrapperCol: {
				xs: { span: 24 },
				sm: { span: 20 },
			},
		};
		const formItemLayoutWithOutLabel = {
			wrapperCol: {
				xs: { span: 24, offset: 0 },
				sm: { span: 20, offset: 2 },
			},
		};
		const formItems = apiInfo.requestFields.map((k, index) => (
			<Form.Item
				{...formItemLayout}
				label={k.id + "(" + k.name + ")"}
				required
				key={index}
				style={{ textAlign: "left" }}>
				{getFieldDecorator(k.id, {
					validateTrigger: ["onChange", "onBlur"],
					rules: [
						{
							required: true,
							whitespace: true,
							message: "参数不可为空",
						},
					],
				})(
					<Input
						placeholder='请输入字段对应的参数值'
						style={{ width: "60%", marginRight: 8 }}
					/>
				)}
			</Form.Item>
		));

		return (
			<Suspense fallback={<PageLoading />}>
				<PageHeaderWrapper>
					<Row className={styles.colorBackground}>
						<Col style={{ padding: 10 }} xs={5}>
							<div className={styles.title}>
								<FormattedMessage id='app.customApi.test' />
							</div>
						</Col>
						<div
							style={{
								float: "right",
								paddingTop: 16,
								paddingRight: 20,
								color: "rgb(21,144,255)",
								cursor: "pointer",
							}}
							onClick={() => this.backList()}>
							<Icon type='bars' style={{ marginRight: 5 }} />
							<FormattedMessage id='app.customApi.backList' />
						</div>
					</Row>
					<Card bordered={false} className={styles.jsonStyle}>
						<Col
							xs={24}
							style={{
								borderLeft: "5px solid #222",
								paddingLeft: 5,
								marginBottom: 20,
							}}>
							<FormattedMessage id='app.customApi.requestField' />
						</Col>
						<Form onSubmit={this.handleSubmit}>
							{formItems}
							<Form.Item {...formItemLayoutWithOutLabel}>
								<Button
									type='primary'
									htmlType='submit'
									loading={this.state.loading}>
									<FormattedMessage id='app.customApi.requestCommit' />
								</Button>
							</Form.Item>
						</Form>
						<Col
							xs={24}
							style={{
								borderLeft: "5px solid #222",
								paddingLeft: 5,
								marginBottom: 20,
								display: this.state.show ? "block" : "none",
							}}>
							<FormattedMessage id='app.customApi.requestRes' />
						</Col>
						<ReactJson
							src={this.state.result}
							style={{
								display: this.state.show ? "block" : "none",
								marginTop: 70,
								padding: 22,
							}}
							xs={24}
							theme='monokai'
						/>
					</Card>
				</PageHeaderWrapper>
			</Suspense>
		);
	}
}

export default connect(({ user }) => ({
	currentUser: user.currentUser,
}))(Form.create()(ProcessTemplate));
